import cv2
import numpy as np
def max_border_scale(img,dst_img=(256,256)):
    h0, w0 = img.shape[:2]  # orig hw

   
    max_border = max(h0,w0)
    r = max(dst_img) / max_border
    interp = cv2.INTER_AREA if r < 1  else cv2.INTER_LINEAR
#     interp = cv2.INTER_AREA 
    img = cv2.resize(img, (int(w0 * r), int(h0 * r)), interpolation=interp)
#     img = cv2.resize(img, (2560, 1440), interpolation=interp)
    return img
#     cv2.imshow("img",img)
#     cv2.waitKey(0)
#     return img, (h0, w0), img.shape[:2]  # img, hw_original, hw_resized



def letterbox(im, new_shape=(256, 256), color=(0, 0, 0), auto=False, scaleFill=False, scaleup=True, stride=32):
    # Resize and pad image while meeting stride-multiple constraints
    shape = im.shape[:2]  # current shape [height, width]
    if isinstance(new_shape, int):
        new_shape = (new_shape, new_shape)

    # Scale ratio (new / old)
    r = min(new_shape[0] / shape[0], new_shape[1] / shape[1])
    if not scaleup:  # only scale down, do not scale up (for better val mAP)
        r = min(r, 1.0)

    # Compute padding
    ratio = r, r  # width, height ratios
    new_unpad = int(round(shape[1] * r)), int(round(shape[0] * r))
    dw, dh = new_shape[1] - new_unpad[0], new_shape[0] - new_unpad[1]  # wh padding
    if auto:  # minimum rectangle
        dw, dh = np.mod(dw, stride), np.mod(dh, stride)  # wh padding
    elif scaleFill:  # stretch
        dw, dh = 0.0, 0.0
        new_unpad = (new_shape[1], new_shape[0])
        ratio = new_shape[1] / shape[1], new_shape[0] / shape[0]  # width, height ratios

    dw /= 2  # divide padding into 2 sides
    dh /= 2

    if shape[::-1] != new_unpad:  # resize
        im = cv2.resize(im, new_unpad, interpolation=cv2.INTER_LINEAR)
    top, bottom = int(round(dh - 0.1)), int(round(dh + 0.1))
    left, right = int(round(dw - 0.1)), int(round(dw + 0.1))
    im = cv2.copyMakeBorder(im, top, bottom, left, right, cv2.BORDER_CONSTANT, value=color)  # add border
    return im


img_path = r'image/my.jpg'

# image = load_image(img_path)
img = cv2.imread(img_path)
img = max_border_scale(img)
cv2.imwrite('result_image/max_border_scale.jpg',img)
letter_img = letterbox(img)

cv2.imwrite('result_image/letter_box.jpg',letter_img)